package com.example.question.tree.tree1;

/**
 * @Date 2023-07-09
 * @Author Jonathan
 */
public class Code08_110 {
    public static void main(String[] args) {

    }

    public boolean isBalanced(TreeNode root) {
        return process1(root) >= 0;
    }

    public boolean isBalanced1(TreeNode root) {
        return process(root).isBalanced;
    }

    private Info process(TreeNode node) {
        if (node == null) {
            return new Info(0, true);
        }

        Info left = process(node.left);
        Info right = process(node.right);
        int maxDepth = Math.max(left.maxDepth, right.maxDepth) + 1;
        boolean isBalanced = left.isBalanced && right.isBalanced && (Math.abs(left.maxDepth - right.maxDepth) <= 1);
        return new Info(maxDepth, isBalanced);
    }

    private int process1(TreeNode root) {
        if (root == null) return 0;
        int left = process1(root.left);
        int right = process1(root.right);
        if (left == -1 || right == -1) {
            return -1;
        }
        if (Math.abs(left - right) > 1) {
            return -1;
        }
        return Math.max(left, right) + 1;
    }


    static class Info {
        private int maxDepth;
        private boolean isBalanced;

        public Info(int maxDepth, boolean isBalanced) {
            this.maxDepth = maxDepth;
            this.isBalanced = isBalanced;
        }
    }
}
